<!--
 * @Author: 宋杰
 * @Date: 2021-01-14 15:30:54
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-01-27 16:22:10
 * @Description: 一家十一口(猜一字) 平台管理员登录页
-->
<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">平台管理员</h3>
        <el-button class="returnHome" @click="returnHome">返 回</el-button>
      </div>

      <div class="conbox">
        <!-- 用户名 -->
        <el-form-item prop="username" class="formbox">
          <div class="iconbox">
            <img src="../../static/img/user.png" alt="" />
          </div>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="Username"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password" class="formbox">
          <div class="iconbox">
            <img src="../../static/img/password.png" alt="" />
          </div>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="Password"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <div class="show-pwd iconbox" @click="showPwd">
            <img
              :src="
                passwordType === 'password'
                  ? require('../../static/img/open.png')
                  : require('../../static/img/open2.png')
              "
            />
          </div>
        </el-form-item>
      </div>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 15px; font-size: 16px"
        @click="login()"
        >登 录</el-button
      >
    </el-form>

    <!-- footer -->
    <div class="footers">
      <div class="footer-center">
        版权所有©江苏省建设教育协会 地址：南京市南通路118号茂悦港5号楼8楼
        邮编：210036 苏ICP备17047788号
      </div>
    </div>
  </div>
</template>

<script>
// import { validUsername } from "@/utils/validate"; // 用户名
import { adminRoutes, institutionRoutes } from "@/router/index.js";

export default {
  name: "Login",
  data() {
    // 用户名提示语
    const validateUsername = (rule, value, callback) => {
      //   if (!validUsername(value)) {
      //     callback(new Error("请输入正确的用户名"));
      //   } else {
      //     callback();
      //   }
    };
    // 密码提示语句
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位数字"));
      } else {
        callback();
      }
    };
    return {
      // showLoading: true, // 显示loading
      imgUrl: require("../../static/img/guanliy.png"), // 背景图片地址

      loginForm: {
        username: "admin", //用户名
        password: "admin123", //密码password
        schoolname: "666666" // 学校机构名
      },
      // 表单验证的功能
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
        // schoolname: [
        //   { required: true, trigger: "blur", validator: validateSchoolname }
        // ],
      },
      // 加载
      loading: false,
      // 查看密码
      passwordType: "password",
      redirect: undefined
    };
  },
  components: {},
  watch: {
    // 在后台登录系统的登陆界面见过这几行代码：
    // 因为有immediate: true 说明加载登录页面时就会执行handler函数，handler的第一个参数表示to,
    // 所以上述代码的意义就是，加载登录页后，直接获取，登录页地址栏的的redirect参数，赋值给this.redirect
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  methods: {
    // 转跳到 "管理员首页" 或 "机构用户首页"
    login() {
      // this.$router.addRoutes(adminRoutes);
      // this.$router.push({ name: "assessmentAudit" });

      let loginFormA = {
        username: this.loginForm.username,
        password: this.loginForm.password
      };
      this.$post("login", loginFormA)
        .then(res => {
          console.log("res", res);
          if (res.code === 200) {
            this.$router.addRoutes(adminRoutes);
            this.$router.push({ name: "assessmentAudit" });
            //全局存储token
            window.sessionStorage["token"] = res.token;
            console.log("window.sessionStorage", window.sessionStorage);
          } else {
            this.$Message.error("登录失败");
          }
        })
        .catch(err => {
          console.log("err", err);
          console.log("登录失败");
        });

      // debugger
      // console.log('loginForm',this.loginForm)
      // if (val == 1) {
      //   this.$router.addRoutes(adminRoutes);
      //   this.$router.push({ name: "assessmentAudit" });
      // } else {
      //   this.$router.addRoutes(institutionRoutes);
      //   this.$router.push({ name: "HomePage" });
      // }
    },

    // 点击查看密码
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        // this.$nextTick()可以等待dom生成以后再来获取dom对象 ,this.$nextTick()在页面交互，尤其是从后台获取数据后重新生成dom对象之后的操作有很大的优势
        // focus()当元素获得焦点时触发
        this.$refs.password.focus();
      });
    },

    //这个的调get提交方式的接口的案例。
    Type() {
      var that = this;
      this.loading = true;
      that
        .$fetch("/dbTypes", {
          //这里的that.$fetch就是对应的http.js里面封装的get
          user_id: this.form.user_id,
          sign: this.form.sign,
          per_page: "6",
          page: "1",
          timestamp: this.form.timestamp
        })
        .then(data => {
          this.loading = false;
          if (data) {
            console.log(data);
            this.typeData = data.dbtypes;
          }
        });
    },
    //这个的调post提交方式的接口的案例。
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.form);
          this.$post("/db", this.form).then(res => {
            //这里的that.$post就是对应的http.js里面封装的post
            if (res.err_code === 1) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.doCancle();
            } else {
              this.$message({
                message: res.msg,
                type: "warning"
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //这个的调put提交方式的接口的案例。

    onSubmit(formName) {
      var id = this.$route.query.id;
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.editForm);
          (this.editForm.timestamp = this.time),
            (this.editForm.sign = this.signs),
            (this.editForm.user_id = this.id);
          this.$put(`/db/${id}`, this.editForm).then(res => {
            //这里的that.$put就是对应的http.js里面封装的put
            if (res.err_code === 1) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.doCancle();
            } else {
              this.$message({
                message: res.msg,
                type: "warning"
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //这个是删除接口cut
    doDelete(item) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var ids = [];
          item.forEach(element => {
            ids.push(element.id);
          });
          console.log({
            ids: ids,
            user_id: this.user_id,
            sign: this.sign,
            timestamp: this.nowtime
          });
          this.$cut("/dbTypes", {
            data: {
              ids: ids,
              user_id: this.user_id,
              sign: this.sign,
              timestamp: this.nowtime
            }
          }) //这里的that.$cut就是对应的http.js里面封装的cut
            .then(res => {
              if (res.err_code === 1) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.List();
              } else {
                this.$message({
                  type: res.msg,
                  message: "删除失败!"
                });
              }
            });
        })
        .catch(() => {});
    },

    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              if (this.show == 1) {
                this.$router.addRoutes(adminRoutes);
              } else {
                this.$router.addRoutes(institutionRoutes);
              }
              debugger;
              this.$router.push({ path: this.redirect || "/" });
              // this.loading = false;
            })
            .catch(() => {
              // this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 返回按钮
    returnHome() {
      this.$router.push({ name: "touristsinfo" });
    }
  },
  mounted() {
    // let bgImg = new Image();
    // bgImg.src = this.imgUrl; // 获取背景图片的url
    // bgImg.onerror = () => {
    //   console.log("img onerror");
    // };
    // bgImg.onload = () => {
    //   // 等背景图片加载成功后 去除loading
    //   this.showLoading = false;
    // };
  }
};
</script>
<style scoped>
.login-container .el-input input {
  color: #000;
}
/* input盒子 */
.el-input {
  display: inline-block;
  height: 47px;
  width: 80%;
  display: flex;
  align-items: center;
}
input {
  background: transparent;
  border: 0px;
  -webkit-appearance: none;
  border-radius: 0px;
  padding: 12px 5px 12px 15px;
  color: #000;
  height: 47px;
  caret-color: #000;
}
.el-input > :nth-child(1) {
  border: none;
}

input:-webkit-autofill {
  box-shadow: 0 0 0px 1000px #283443 inset !important;
  -webkit-text-fill-color: #000 !important;
}
/* 输入框父盒子 */
.el-form-item {
  border: 1px solid rgba(200, 200, 200, 0.3);
  background: #fff;
  border-radius: 5px;
  color: #454545;
}
.el-form-item > :nth-child(1) {
  display: flex;
  align-items: center;
}
/* 学校选择 */
.el-select {
  width: 100%;
}
.el-select > :nth-child(1) > :nth-child(1) {
  border: none !important;
}
/* 学校选择end */

/* 图片盒子 */
.iconbox {
  display: flex;
  align-items: center;
}
.iconbox > img {
  width: 20px;
  margin: 0 10px;
}
.login-container {
  position: relative;
  min-height: 100%;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: url("../../static/img/guanliy.png") no-repeat;
  background-size: 100% 70%;
}

/* 登录方块的最外层div */
.login-form {
  position: absolute;
  top: calc(50% - 250px);
  left: calc(50% - 250px);
  width: 500px;
  height: 500px;
  max-width: 100%;
  z-index: 3;
  padding: 0 35px;
  margin: 0 auto;
  border-radius: 10px;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0px 0px 30px 10px #abcdef70;
}
.conbox {
  min-height: 45%;
}
.tips {
  font-size: 14px;
  color: #000;
  margin-bottom: 10px;
}
.tips > span:first-of-type {
  margin-right: 16px;
}
.title-container {
  position: relative;
  margin-top: 15%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title {
  font-size: 16px;
  color: #000;
  margin: 0px auto 40px auto;
  text-align: center;
  font-weight: bold;
  border-bottom: 0px solid #1e486f59;
}

.title.is-active {
  color: #409eff;
  border-bottom: 2px solid #409eff;
}
.footers {
  position: fixed;
  bottom: 0;
  background-color: #093b69;
  text-decoration: none;
  width: 100%;
  z-index: 999;
}
.footer-center {
  float: none;
  margin: 0;
  color: #fff;
  text-align: center;
  text-decoration: none;
  padding: 0.5% 0;
  line-height: 30px;
  font-size: 12px;
  vertical-align: middle;
}

/* 返回首页按钮 */
.returnHome {
  position: absolute;
  top: -50px;
  left: -20px;
  padding: 10px 15px;
  /* border: none !important; */
  font-size: 16px;
  opacity: 0.8;
}
/* 返回首页按钮 */
</style>
